package com.kaung.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CookieDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //Chrome里加这个话才能不显示为乱码
        resp.setContentType("text/html");

        PrintWriter out = resp.getWriter();

        //服务器从客户端获取cookie
        Cookie[] cookies = req.getCookies();

        //判断cookie是否存在
        if (cookies!=null){
            //如果存在
            out.write("您上一次访问的时间是：");

            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie=cookies[i];
                //获取cookie的名字
                if(cookie.getName().equals("name")){
                    System.out.println(cookie.getValue());
                }
            }
        }else {
            out.write("这是您第一次访问本站！");
        }


        //服务器给客户端一个cookie
       // Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
        //设置cookie的有效期
       // cookie.setMaxAge(24*60*60);
        Cookie cookie = new Cookie("name", "清姜");
        resp.addCookie(cookie);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
